/*
 *		source/launcher.js - Application launcher
 */

/* tazLoader - Download manager
 * Copyright (C) 2011 Timo Tegtmeier
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 3
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

enyo.kind({

	name:			"AppLauncher",
	kind:			"Component",

	kAlarmKey:		"com.tegistuff.tazloader.timer",
	kCookieName:	"comtegistuffapptazloader",
	kDownloadPath:	"/media/internal/taz/",

	downloading:	false,

	components: [{
		name:		"appMgr",
		kind: 		"PalmService",
		service:	"palm://com.palm.applicationManager/",
		method:		"open",
		subscribe:	true
	}, {
		name:		"downloader",
		kind:		"PalmService",
		service:	"palm://com.palm.downloadmanager/",
		subscribe:	true,
		method:		"download",
		onSuccess:	"downloadSuccess",
		onFailure:	"downloadFailed"
	}, {
		name:		"setAlarm",
		kind:		"PalmService",
		service:	"palm://com.palm.power/timeout/",
		onSuccess:	"setTimerSuccess",
		onFailure:	"setTimerFailed"
	}, {
		name:		"powerService",
		kind:		"PalmService",
		service:	"palm://com.palm.power/com/palm/power/",
		subscribe:	true
	}, {
		kind: 					"ApplicationEvents",
		onApplicationRelaunch:	"relaunch"
	}],

	//
	// Event handling
	//

	downloadSuccess: function(sender, response) {
		if(response.completed) {
			this.log("SCHEDULED DOWNLOAD success");
			this.setTimer(this.getSettings());
			this.closeDashboard();
			this.leaveActivity();
		}
	},

	downloadFailed: function() {
		this.log("SCHEDULED DOWNLOAD FAILED");
		this.setTimer(this.getSettings());
		this.closeDashboard();
		this.leaveActivity();
		this.downloading = false;
	},

	setTimerSuccess: function() {
		this.log("TIMER> set successfully");
	},

	setTimerFailed: function() {
		this.error("TIMER> Failed to set");
	},

	//
	// (Re-)Start handling
	//

	startup: function() {
		// Set some globals.
		enyo.application.appName 		= "tazLoader";
		enyo.application.appAuthor 		= "Timo Tegtmeier";
		enyo.application.versionString 	= "1.0.0";
		enyo.application.versionInt 	= 1;
		enyo.application.copyrightYears	= "2011";

		enyo.application.kAlarmKey = this.kAlarmKey;
		enyo.application.kCookieName = this.kCookieName;
		enyo.application.kDownloadPath = this.kDownloadPath;

		enyo.application.openFile = enyo.bind(this, this.openFile);
		enyo.application.getSettings = enyo.bind(this, this.getSettings);
		enyo.application.saveSettings = enyo.bind(this, this.saveSettings);
		enyo.application.getDownloadDetailsFromDate = enyo.bind(this, this.getDownloadDetailsFromDate);

		// Create the necessary helper objects.
		enyo.application.connChecker = new ConnectionChecker();

		// Launch the application
		enyo.application.launcher.relaunch(this);
	},

	relaunch: function(sender) {
		var params = enyo.windowParams;
 		if(params.action && (params.action = "doDownload")) {
			this.download();
		} else {
			this.openMainView(params);
		}
		return true;
	},

	//
	// Automatic downloading
	//

	enterActivity: function() {
		this.$.powerService.call({
			id:				"com.tegistuff.app.tazloader",
			duration_ms: 	240000
		}, {
			method:		"activityStart"
		});
	},

	leaveActivity: function() {
		this.$.powerService.call({
			id:			"com.tegistuff.app.tazloader"
		}, {
			method: 	"activityEnd"
		});
	},

	download: function() {
		// Check if we are already downloading.
		if(this.downloading) {
			return;
		}

		// Check if auto-downloading is enabled.
		var settings = this.getSettings();
		if(!settings.autoEnabled) {
			return;
		}

		var date = new Date();
		if(date.getDay() > 0) {
			this.enterActivity();
			this.openDashboard();
			this.downloading = true;

			var params = this.getDownloadDetailsFromDate(date, settings);
			this.$.downloader.call({
				 target: 					params.url,
				 mime: 						"application/pdf",
				 targetDir : 				this.kDownloadPath,
				 targetFilename : 			params.fileName,
				 keepFilenameOnRedirect:	true,
				 canHandlePause: 			true
			});
		} else {
			this.log("No download today: It's sunday!");
			this.setTimer(settings);
		}
	},

	setTimer: function(settings) {
		if(settings && settings.autoEnabled) {
			var d = new Date();

			// Check wether the date lies in the future.
			if((d.getHours() > settings.autoTimeHour) ||
			   ((d.getHours() == settings.autoTimeHour) && (d.getMinutes() + 3 >= settings.autoTimeMin))) {
				// Schedule for the next day.
				this.log("Scheduling download for tomorrow");
				d.setTime(d.getTime() + (1000 * 60 * 60 * 24));
			}

			// Apply download time.
			d.setHours(settings.autoTimeHour);
			d.setMinutes(settings.autoTimeMin);
			d.setSeconds(0);

			// Alarm time needs to be specified as UTC time.
			var year = d.getUTCFullYear();
			var month = d.getUTCMonth() + 1;
			var day = d.getUTCDate();
			var hours = d.getUTCHours();
			var minutes = d.getUTCMinutes();

			var alarmTime = enyo.macroize("{$mm}/{$dd}/{$yyyy} {$h}:{$m}:00", {
				mm:		month < 10 ? '0' + month : month,
				dd:		day < 10 ? '0' + day : day,
				yyyy:	year,
				h:		hours < 10 ? '0' + hours : hours,
				m:		minutes < 10 ? '0' + minutes : minutes
			});

			// Setup the alarm.
			this.$.setAlarm.call({
				"key":		this.kAlarmKey,
				"at":		alarmTime,
				"wakeup":	true,
				"uri":		"palm://com.palm.applicationManager/open",
				"params": {
					"id":	"com.tegistuff.app.tazloader",
					"params": {
						"action": "doDownload"
					}
				}
			}, {
				method:		"set"
			});
        } else {
			this.$.setAlarm.call({
				"key": this.kAlarmKey
			}, {
				method:		"clear"
			});
		}
	},

	//
	// Mainview handling
	//

	openMainView: function() {
		enyo.windows.activate("source/mainview/index.html", "MainView");
	},

	//
	// Dashboard
	//

	openDashboard: function() {
		return enyo.windows.openDashboard("source/dashboard/index.html", "dashboard");
	},

	closeDashboard: function() {
		var dbWindow = enyo.windows.fetchWindow("dashboard");
		if(dbWindow) {
			dbWindow.close();
		}
	},

	//
	// Helper functions
	//

	openFile: function(path) {
		this.$.appMgr.call({
			target: path
		});
	},

	getWithTrailingZero: function(x) {
		if(x) {
			return x < 10 ? "0" + x : x;
		} else {
			return "00";
		}
	},

	getDownloadDetailsFromDate: function(date, settings) {
		settings = settings || this.getSettings();

		var month = date.getMonth() + 1;
		var issueNo = date.getFullYear() + '_' + this.getWithTrailingZero(month) + '_' + this.getWithTrailingZero(date.getDate());
		var fileName = issueNo + ".pdf";
		var credentials = settings.username + ":" + settings.password;
		var url = "http://" + credentials + "@dl.taz.de/taz/abo/get.php?f=" + fileName;

		return ({
			issueNo:	issueNo,
			fileName:	fileName,
			url:		url
		});
	},

	//
	// Settings
	//

	saveSettings: function(settings) {
		enyo.setCookie(this.kCookieName, enyo.json.stringify(settings));
		this.setTimer(settings);
	},

	getSettings: function() {
		var cookie = enyo.getCookie(this.kCookieName);
		if(cookie) {
			return enyo.json.parse(cookie);
		}
		return ({
			username:		"",
			password:		"",
			autoOpen:		true,
			autoEnabled:	true,
			autoTimeMin:	0,
			autoTimeHour:	2
		});
	}
});
